﻿using MongoDB.Driver;
using Sustainalytics.Utils;
using Sustainalytics.Utils.Serilog;
using System;
using System.IO;

namespace Sustainalytics.DataLayer
{
    /// <remarks>
    /// Stores to MongoDBGridFS
    /// </remarks>
    public class FileRepository : IFileRepository
    {
        private readonly string databaseName;
        private readonly MongoGridFSHelper mongoGridFSHelper;

        public FileRepository(string cnxStringMongo)
        {
            if (string.IsNullOrEmpty(cnxStringMongo))
                throw new ArgumentException("cnxStringMongo");

            var url = new MongoUrl(cnxStringMongo);
            if (string.IsNullOrEmpty(url.DatabaseName))
                throw new ArgumentException("databaseName");

            var mongoClient = new MongoClient(cnxStringMongo);
            var database = mongoClient.GetDatabase(url.DatabaseName);
            databaseName = url.DatabaseName;
            mongoGridFSHelper = new MongoGridFSHelper(database);
        }

        public virtual Tuple<Stream, string, string> GetDownloadStream(Guid id)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("id");

            var ret = mongoGridFSHelper.OpenDownloadStream(id);
            return ret;
        }

        public virtual Tuple<Stream, Guid> UploadFile(Guid id, string fileName, string contentType)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("id");

            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException("fileName");

            if (string.IsNullOrEmpty(contentType))
                throw new ArgumentNullException("contentType");

            var ret = mongoGridFSHelper.OpenUploadStream(fileName, id, contentType);
            return ret;
        }

        public virtual Tuple<Stream, Guid> UpdateFile(Guid id, Guid newId, string fileName, string contentType)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("id");

            if (newId == Guid.Empty)
                throw new ArgumentNullException("newId");

            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException("fileName");

            if (string.IsNullOrEmpty(contentType))
                throw new ArgumentNullException("contentType");

            var ret = mongoGridFSHelper.UpdateFile(fileName, id, newId, contentType);
            return ret;
        }
    }
}
